package com.lagou.rabbitmq.service.impl;

import com.lagou.rabbitmq.entity.Order;
import com.lagou.rabbitmq.mapper.OrderMapper;
import com.lagou.rabbitmq.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName OrderServiceImpl
 * @Description
 * @Author playboy
 * @Date 2021/8/28 8:14 下午
 * @Version 1.0
 **/
@Service
public class OrderServiceImpl implements OrderService {
	private static Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private AmqpTemplate amqpTemplate;

	private AtomicInteger orderNo = new AtomicInteger(0);


	@Override
	public Order pay(String id) {
		Map map = new HashMap();
		map.put("id",Long.parseLong(id));
		map.put("newStatus","03");
		map.put("oldStatus","00");

		int i = orderMapper.updateByIdAndStatus(map);
		Order order = orderMapper.selectById(Long.parseLong(id));

		return order;
	}

	@Override
	public Order save(Order order) {
		Random random = new Random();
		int i = random.nextInt(10000);
		int andIncrement = orderNo.incrementAndGet();
		String format = String.format("%06d", andIncrement);//其中0表示补零而不是补空格，6表示至少6位
		order.setOrderNo(format);
		order.setId(Long.parseLong(i+""));
		orderMapper.insert(order);


		Message message = MessageBuilder.withBody(Long.toString(order.getId()).getBytes(StandardCharsets.UTF_8)).build();

		//发送消息到过期队列
		amqpTemplate.send("ex.pay.ttl","order",message);


		return order;
	}

	@Override
	public Order get(String id) {
		Order order = orderMapper.selectById(Long.parseLong(id));
		return order;
	}
}
